// controller.js - 增强后的最终版本 (支持立即恢复调度)

// 获取插件资源的 URL 前缀
const extensionUrlBase = `chrome-extension://${chrome.runtime.id}`;
const GLOBAL_STORAGE_KEY = 'ruleActEnabled';

let isEngineEnabled = true;
const activeTimers = new Map();
const executionMap = new Map();

/**
 * 通过 Service Worker 获取初始全局开关状态。
 */
async function getInitialState() {
    return new Promise((resolve) => {
        // 向 background.js 发送请求，获取当前全局开关状态
        chrome.runtime.sendMessage({ action: 'GET_GLOBAL_STATE' }, (response) => {
            // response.isEnabled 包含 Service Worker 返回的状态
            resolve(response ? response.isEnabled : true);
        });
    });
}

// ----------------------------------------------------
// 新增：核心调度逻辑，可重复调用
// ----------------------------------------------------

async function startScheduling() {
    const currentUrl = window.location.href;

    // 动态导入 rule.js
    const ruleModule = await import(`${extensionUrlBase}/rule.js`);
    const rules = ruleModule.rules;
    const simpleUrlMatch = ruleModule.simpleUrlMatch;

    for (const rule of rules) {
        if (!simpleUrlMatch(rule.urlMatch, currentUrl)) {
            continue;
        }

        const isRepeating = rule.maxExecutions > 1 || rule.maxExecutions === Infinity;

        // 关键：只处理符合条件的重复任务，并且该任务当前没有活动的计时器
        if (isRepeating && rule.intervalMs && rule.intervalMs > 0 && !activeTimers.has(rule.name)) {

            // 检查：如果 maxExecutions 是有限的且已经执行完毕，则不重启
            const currentCount = executionMap.get(rule.name) || 0;
            if (currentCount >= rule.maxExecutions && rule.maxExecutions !== Infinity) {
                console.log(`[Controller] Rule ${rule.name} already finished (${rule.maxExecutions} runs). Skipping restart.`);
                continue;
            }

            console.log(`[Controller] Matched repeating rule: ${rule.name}. Restarting schedule immediately.`);

            // 立即执行第一次
            await executeRuleLogic(rule);

            // 调度后续执行
            scheduleNextExecution(rule);
        }
    }
}


// ----------------------------------------------------
// 新增：接收 Service Worker 的消息 (修复启用逻辑)
// ----------------------------------------------------

chrome.runtime.onMessage.addListener((message) => {
    if (message.action === 'UPDATE_GLOBAL_STATE') {

        if (message.isEnabled === true) {
            // 启用逻辑：立即重启调度
            isEngineEnabled = true;
            console.log("[Controller] Global state updated: true. Attempting to restart suspended schedules...");
            startScheduling(); // 🚀 核心：调用 startScheduling 恢复任务

        } else {
            // 禁用逻辑：清除定时器
            isEngineEnabled = false;
            activeTimers.forEach(timerId => clearTimeout(timerId));
            activeTimers.clear();
            console.log("[Controller] Global state updated: false. All periodic tasks suspended.");
        }
    }
});


// ----------------------------------------------------
// 递归 setTimeout 调度函数 (检查全局开关)
// ----------------------------------------------------

function scheduleNextExecution(rule) {

    if (!isEngineEnabled) {
        console.log(`[Controller] Rule ${rule.name} suspended by global switch.`);
        // 定时器 ID 仍保留在 activeTimers 中，直到被禁用逻辑清除
        return;
    }

    const currentCount = executionMap.get(rule.name) || 0;

    if (currentCount >= rule.maxExecutions && rule.maxExecutions !== Infinity) {
        console.log(`[Controller] Rule ${rule.name} reached max executions (${rule.maxExecutions}). Scheduling stopped.`);
        return;
    }

    // 调度下一次执行
    const timerId = setTimeout(async () => {

        // 执行当前逻辑
        await executeRuleLogic(rule);

        // 调度再下一次执行（递归调用）
        scheduleNextExecution(rule);

        // 调度成功后，从 Map 中删除旧的 timerId (非必须，因为 scheduleNextExecution 会创建新 ID)
        // activeTimers.delete(rule.name);

    }, rule.intervalMs);

    // 存储定时器 ID 以便清除
    activeTimers.set(rule.name, timerId);
}


// ----------------------------------------------------
// 执行器的加载、运行、计数和错误处理逻辑
// ----------------------------------------------------

/**
 * 加载并执行单个规则对应的执行器逻辑。
 */
async function executeRuleLogic(rule) {
    const executorPath = `${extensionUrlBase}/executors/${rule.executorName}.js`;

    // 增加执行计数（无论成功或失败，都视为一次执行完成）
    const currentCount = executionMap.get(rule.name) || 0;
    executionMap.set(rule.name, currentCount + 1);

    try {
        const executorModule = await import(executorPath);

        if (typeof executorModule.execute === 'function') {
            await executorModule.execute(rule);
        } else {
            console.error(`[RuleAct V3 Error] Executor ${rule.executorName} is missing the 'execute' function.`);
        }
    } catch (error) {
        console.error(`[RuleAct V3 Error] Execution failed for rule: ${rule.name}.`, error);
    }

    return true;
}


// ----------------------------------------------------
// run() 函数 (入口：调用 startScheduling)
// ----------------------------------------------------

export async function run() {
    // 首次运行时，通过 Service Worker 读取初始状态
    isEngineEnabled = await getInitialState();

    if (!isEngineEnabled) {
        console.log("[Controller] Engine is globally disabled. Skipping all scheduled runs.");
        return;
    }

    // 首次运行时，启动调度
    await startScheduling();

    // 此外，还需要处理单次运行任务的逻辑（它们在 startScheduling 中被跳过）
    // 为了完整性，这里单独处理单次运行的任务：
    const ruleModule = await import(`${extensionUrlBase}/rule.js`);
    const rules = ruleModule.rules;
    const simpleUrlMatch = ruleModule.simpleUrlMatch;
    const currentUrl = window.location.href;

    for (const rule of rules) {
        if (rule.maxExecutions === 1 && simpleUrlMatch(rule.urlMatch, currentUrl)) {
            // 确保单次运行任务只在页面加载时运行，并且只运行一次
            if ((executionMap.get(rule.name) || 0) === 0) {
                console.log(`[Controller] Matched single-run rule: ${rule.name}. Running once.`);
                await executeRuleLogic(rule);
            }
        }
    }
}